﻿using System;
using Castle.MicroKernel;
using Castle.Core;

namespace FamilyTreeProject.Web.Components
{
    internal class CastleServiceContainer : IServiceContainer 
    {
        #region Private Members

        private IKernel kernel;

        #endregion

        #region Constructors

        public CastleServiceContainer(IKernel kernel)
        {
            this.kernel = kernel;
        }

        #endregion

        #region IServiceContainer Members

        public TService GetService<TService>()
        {
            return (TService)GetService(typeof(TService));
        }

        #endregion

        #region IServiceProvider Members

        public object GetService(Type serviceType)
        {
            try
            {
                return kernel.Resolve(serviceType);
            }
            catch (ComponentNotFoundException)
            {
                if (serviceType.IsClass && !serviceType.IsAbstract)
                {
                    kernel.AddComponent(serviceType.FullName, serviceType, LifestyleType.Transient);
                    return kernel.Resolve(serviceType);
                }
                else
                    throw;
            }
        }

        #endregion
    }
}
